import { getToken, setToken, getUser, setUser,removeToken } from "@/utils/auth"
import { login, getUserInfo,logout } from "@/api/login"
import { reject, resolve } from "core-js/fn/promise"

const user = {
    state: {
        token: getToken(),
        user: getUser()
        // token: null,
        // user: null
    },

    mutations: {
        SET_TOKEN(state, token) {
            state.token = token
            //将token保存到localstorage里面，因为路由跳转前（参考permission.js）需要从localstorage里面获取token
            setToken(token)
            //解决问题：跳转路由不需要获取token
            // 但刷新后localstorage里没有信息，需保存
        },
        SET_USER(state, user) {
            state.user = user
            //将用户信息保存到localstorage里面
            setUser(user)
        }
    },

    actions: {
        // 登录获取token
        Login({ commit }, form) {
            return new Promise((resolve, reject) => {
                login(form.username.trim(), form.password).then(response => {
                    const resp = response.data
                    commit("SET_TOKEN", resp.data.token)
                    resolve(resp)
                })
            }).catch(error => {
                reject(error)
            })
        },

        //通过token获取用户信息
        GetUserInfo({ commit, state }) {
            return new Promise((resolve, reject) => {
                getUserInfo(state.token).then(response => {
                    const respUser = response.data
                    // console.log("response.data", respUser)
                    commit("SET_USER", respUser.data)
                    resolve(respUser)
                }).catch(error => {
                    reject(error)
                })
            })
        },

        //退出系统
        Logout({ commit, state }) {
            return new Promise((resolve, reject) => {
                logout(state.token).then(response => {
                    const resp = response.data
                    commit("SET_TOKEN", '')
                    commit("SET_USER", null)
                    removeToken()
                    resolve(resp)
                }).catch(error => {
                    reject(error)
                })
            })
        }
    }
}

export default user